package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.POJO.Setmeal;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] ids){
        try {
            String img = setmeal.getImg();
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
            setmealService.add(setmeal,ids);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch (Exception e) {

            e.printStackTrace();
            return new Result(true, MessageConstant.ADD_SETMEAL_FAIL);

        }
    }
    //文件上传
    @RequestMapping("/upload")//前端传入一个文件
    public Result upload(@RequestParam("imgFile")MultipartFile multipartFile){
        try {//获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            int i = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(i - 1);
            //重新组合文件名
            String fileName= UUID.randomUUID().toString().replace("-","")+suffix;
            //使用七牛云上传图片
            QiniuUtils.upload2Qiniu(multipartFile.getBytes(),fileName);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        }catch (Exception e) {

            e.printStackTrace();
            return new Result(true, MessageConstant.PIC_UPLOAD_FAIL);

        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){

            PageResult pageResult=setmealService.findPage(queryPageBean);
            return pageResult;

    }
}
